import { Card, Table, Row, Col, Tag, Input, Select, Button, Typography, Statistic } from '@/utils/antd-imports';
import { SearchOutlined, FilterOutlined } from '@/utils/icons';
import React from 'react';







import DatePicker from 'antd/es/date-picker';


import { Pie, Bar } from '@ant-design/charts';


const { Text } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;

export const StatisticsTab = ({ subProjectsData = [] }) => {
  // 状态筛选
  const [filters, setFilters] = React.useState({
    name: '',
    clientName: '',
    status: '',
    projectType: '',
    dateRange: []
  });

  // 处理筛选变化
  const handleFilterChange = (key, value) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  // 筛选数据
  const filteredData = subProjectsData.filter(project => {
    return (
      (!filters.name || project.name.includes(filters.name)) &&
      (!filters.clientName || project.clientName.includes(filters.clientName)) &&
      (!filters.status || project.status === filters.status) &&
      (!filters.projectType || project.projectType === filters.projectType) &&
      (!filters.dateRange || filters.dateRange.length === 0 || (
        new Date(project.expectedEndDate.replace(/\./g, '-')) >= filters.dateRange[0] &&
        new Date(project.expectedEndDate.replace(/\./g, '-')) <= filters.dateRange[1]
      ))
    );
  });

  // 计算关键指标
  const calculateMetrics = () => {
    const totalProjects = filteredData.length;
    const totalBudget = filteredData.reduce((sum, p) => sum + (p.budgetAmount || 0), 0);
    const totalPaid = filteredData.reduce((sum, p) => sum + (p.paidAmount || 0), 0);
    const avgCostRate = filteredData.reduce((sum, p) => sum + (p.costRate || 0), 0) / (totalProjects || 1);
    const completionRate = (filteredData.filter(p => p.status === '已回款').length / (totalProjects || 1)) * 100;

    return {
      totalProjects,
      totalBudget,
      totalPaid,
      avgCostRate,
      completionRate
    };
  };

  const metrics = calculateMetrics();

  // 准备图表数据
  const statusChartData = filteredData.reduce((acc, p) => {
    const existing = acc.find(item => item.status === p.status);
    if (existing) {
      existing.value += 1;
    } else {
      acc.push({ status: p.status, value: 1 });
    }
    return acc;
  }, []);

  const typeChartData = filteredData.reduce((acc, p) => {
    const existing = acc.find(item => item.type === p.projectType);
    if (existing) {
      existing.value += 1;
    } else {
      acc.push({ type: p.projectType, value: 1 });
    }
    return acc;
  }, []);

  // 子项目表格列定义
  const columns = [
    {
      title: '项目ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      render: (id) => <Text strong>{id}</Text>
    },
    {
      title: '子项目名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      render: (text) => <Text strong>{text}</Text>
    },
    {
      title: '客户名称',
      dataIndex: 'clientName',
      key: 'clientName',
      width: 150
    },
    {
      title: '对接人',
      dataIndex: 'contactPerson',
      key: 'contactPerson',
      width: 100
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 100
    },
    {
      title: '科室',
      dataIndex: 'division',
      key: 'division',
      width: 100
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {status}
        </Tag>
      )
    },
    {
      title: '合同号',
      dataIndex: 'contractNumber',
      key: 'contractNumber',
      width: 120
    },
    {
      title: '预算金额',
      dataIndex: 'budgetAmount',
      key: 'budgetAmount',
      width: 120,
      render: (amount) => <Text>¥{(amount || 0).toLocaleString()}</Text>
    },
    {
      title: '已回款',
      dataIndex: 'paidAmount',
      key: 'paidAmount',
      width: 120,
      render: (amount) => <Text>¥{(amount || 0).toLocaleString()}</Text>
    },
    {
      title: '成本率',
      dataIndex: 'costRate',
      key: 'costRate',
      width: 100,
      render: (rate) => (
        <Text type={rate > 0.9 ? 'danger' : rate > 0.7 ? 'warning' : 'success'}>
          {(rate * 100).toFixed(2)}%
        </Text>
      )
    },
    {
      title: '时价',
      dataIndex: 'hourlyRate',
      key: 'hourlyRate',
      width: 100,
      render: (rate) => <Text>¥{rate || 0}</Text>
    },
    {
      title: '预算工时',
      dataIndex: 'budgetHours',
      key: 'budgetHours',
      width: 100,
      render: (hours) => <Text>{hours || 0}h</Text>
    },
    {
      title: '实际工时',
      dataIndex: 'actualHours',
      key: 'actualHours',
      width: 100,
      render: (hours) => <Text>{hours || 0}h</Text>
    },
    {
      title: '预计结束时间',
      dataIndex: 'expectedEndDate',
      key: 'expectedEndDate',
      width: 120
    }
  ];

  return (
    <>
      {/* 关键指标区域 */}
      <div style={{ overflowX: 'auto', marginBottom: 24 }}>
        <div style={{ display: 'flex', minWidth: 'max-content' }}>
          <div style={{ minWidth: '150px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="项目总数"
                value={metrics.totalProjects}
                valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '180px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="总预算金额"
                value={metrics.totalBudget}
                precision={0}
                prefix="¥"
                valueStyle={{ color: '#1890ff', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '180px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="总回款金额"
                value={metrics.totalPaid}
                precision={0}
                prefix="¥"
                valueStyle={{ color: '#52c41a', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '150px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="平均成本率"
                value={metrics.avgCostRate * 100}
                precision={2}
                suffix="%"
                valueStyle={{ color: '#faad14', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '150px' }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="完成率"
                value={metrics.completionRate}
                precision={2}
                suffix="%"
                valueStyle={{ color: '#722ed1', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
        </div>
      </div>

      {/* 图表区域 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="项目状态分布">
            <Pie
              data={statusChartData}
              angleField="value"
              colorField="status"
              radius={0.8}
              label={{
                type: 'inner',
                offset: '-30%',
                content: '{name}',
                style: {
                  fontSize: 14,
                  textAlign: 'center',
                },
              }}
              interactions={[{ type: 'element-active' }]}
              color={({ status }) => getStatusColor(status)}
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card title="项目类型分布">
            <Bar
              data={typeChartData}
              xField="value"
              yField="type"
              seriesField="type"
              color={({ type }) => getProjectTypeColor(type)}
              legend={{
                position: 'top-right',
              }}
            />
          </Card>
        </Col>
      </Row>

      {/* 筛选区域 - 移动到图表下方 */}
      <Card style={{ marginBottom: 24 }}>
        <Row gutter={16}>
          <Col span={6}>
            <Input
              placeholder="搜索项目名称"
              prefix={<SearchOutlined />}
              value={filters.name}
              onChange={e => handleFilterChange('name', e.target.value)}
            />
          </Col>
          <Col span={6}>
            <Input
              placeholder="搜索客户名称"
              prefix={<SearchOutlined />}
              value={filters.clientName}
              onChange={e => handleFilterChange('clientName', e.target.value)}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="项目状态"
              style={{ width: '100%' }}
              value={filters.status}
              onChange={value => handleFilterChange('status', value)}
            >
              <Option value="未验收">未验收</Option>
              <Option value="验收中">验收中</Option>
              <Option value="开票中">开票中</Option>
              <Option value="待回款">待回款</Option>
              <Option value="已回款">已回款</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Select
              placeholder="项目类型"
              style={{ width: '100%' }}
              value={filters.projectType}
              onChange={value => handleFilterChange('projectType', value)}
            >
              <Option value="整包项目">整包项目</Option>
              <Option value="人力项目">人力项目</Option>
              <Option value="分包项目">分包项目</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Button 
              type="primary" 
              icon={<FilterOutlined />}
              onClick={() => setFilters({
                name: '',
                clientName: '',
                status: '',
                projectType: '',
                dateRange: []
              })}
            >
              重置
            </Button>
          </Col>
        </Row>
        <Row gutter={16} style={{ marginTop: 16 }}>
          <Col span={8}>
            <RangePicker 
              style={{ width: '100%' }}
              placeholder={['开始日期', '结束日期']}
              onChange={dates => handleFilterChange('dateRange', dates)}
              value={filters.dateRange}
            />
          </Col>
        </Row>
      </Card>

      {/* 数据表格 */}
      <Table
        columns={columns}
        dataSource={filteredData}
        rowKey="id"
        pagination={{ pageSize: 10 }}
        scroll={{ x: 2000 }}
        bordered
        size="middle"
      />
    </>
  );
};

// 辅助函数
const getStatusColor = (status) => {
  const colors = {
    '未验收': '#888',
    '验收中': '#1890ff',
    '开票中': '#faad14',
    '待回款': '#722ed1',
    '已回款': '#52c41a'
  };
  return colors[status] || '#888';
};

const getProjectTypeColor = (type) => {
  const colors = {
    '整包项目': '#eb2f96',
    '人力项目': '#fa541c',
    '分包项目': '#fa8c16'
  };
  return colors[type] || '#888';
};